const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
const path = require('path');
// 为了提高代码的可维护性和灵活性，将文件路径作为外部配置传入
const CONFIG_PATH = path?.join('./conf', 'config.json');

// 提取重复的文件读取和JSON解析逻辑
async function readConfig() {
  if (!fs || !path) {
    console.warn('Running in non-Electron environment. Using default/fallback configuration.');
    // 返回默认配置或抛出错误，根据您的实际需求决定
    return []; // 假设有一个getDefaultConfig函数提供默认配置
  }

  return new Promise((resolve, reject) => {
    fs.readFile(CONFIG_PATH, 'utf8', (err, data) => {
        if (err) return reject(err);
      resolve(JSON.parse(data));
    });
  });
}

// 提取重复的文件写入逻辑
async function writeConfig(config) {
  return new Promise((resolve, reject) => {
    const updatedJson = JSON.stringify(config, null, 2);
    fs.writeFile(CONFIG_PATH, updatedJson, 'utf8', err => {
      if (err) return reject(err);
      resolve();
    });
  });
}

module.exports.getControlListApi = async function () {
  try {
    const data = await readConfig();
    return { code: 0, result: data };
  } catch (err) {
    return { code: -1, message: err.message };
  }
};

module.exports.deleteControlApi = async function (params) {
  try {
    const configs = await readConfig();
    const index = configs.findIndex(config => config.id === params.id);
    if (index === -1) {
      return { code: -1, message: `No configuration found with ID: ${params.id}` };
    }

    configs.splice(index, 1);
    await writeConfig(configs);
    return { code: 0, result: '', message: 'success' };
  } catch (err) {
    return { code: -1, message: err.message };
  }
};

module.exports.saveControlApi = async function (newConfigData) {
  try {
    let configs;
    if (newConfigData.id) {
      configs = await readConfig();
      const index = configs.findIndex(config => config.id === newConfigData.id);
      if (index === -1) {
        return { code: -1, message: `No configuration found with ID: ${newConfigData.id}` };
      }

      configs[index] = {
        ...configs[index],
        ...newConfigData,
        updateTime: new Date().toISOString(),
      };
    } else {
      configs = await readConfig();
      const newConfig = {
        id: uuidv4(),
        name: newConfigData.name,
        configInfo: newConfigData.configInfo,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
      };
      configs.push(newConfig);
    }

    await writeConfig(configs);
    return { code: 0, result: '', message: 'success' };
  } catch (err) {
    return { code: -1, message: err.message };
  }
};
